package org.szy.core.common.listener;

import cn.hutool.core.convert.Convert;
import com.mybatisflex.annotation.UpdateListener;
import org.noear.solon.core.handle.Context;
import org.szy.core.auth.util.SaLoginUtil;
import org.szy.core.auth.util.SaUtil;
import org.szy.core.common.entity.BaseEntity;
import org.szy.core.common.entity.LoginUser;
import org.szy.core.common.entity.LoginUserMini;
import org.szy.core.common.uilts.IpUtils;

import java.time.LocalDateTime;

/**
 * 监听 entity 的 update 行为
 * 数据填充。
 * 数据修改。
 *
 * @author 孙志阳
 * @date 2023-06-13
 * @since 1.0.0
 **/
public class BaseUpdateListener implements UpdateListener {

    @Override
    public void onUpdate(Object obj) {
        Context ctx = Context.current();
        BaseEntity entity = (BaseEntity) obj;
        entity.setUpdateTime(LocalDateTime.now());
        if (ctx == null) return;
        LoginUserMini user = SaLoginUtil.getLoginUserMini();
        Long userId = -1L;
        if (null != user) {
            userId = Convert.toLong(user.getUserId());
        }
        entity.setUpdateUser(userId);
        entity.setClientIp(IpUtils.getIp(ctx));
    }
}
